package daobeauty.proxy.javassist;

import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;

import org.hibernate.SessionFactory;

import daobeauty.interceptor.MethodInterceptor;
import daobeauty.proxy.ProxyProvider;

/**
 * Created 08.09.2008
 * @author M. Serhat Cinar
 *
 */
public class JavassistProxyProvider implements ProxyProvider {

	/* (non-Javadoc)
	 * @see daobeauty.proxy.ProxyProvider#generateProxy(java.lang.Class[], org.hibernate.SessionFactory, java.lang.Class, java.lang.Object, java.lang.Object[])
	 */
	public Object generateProxy(Class[] interfaces, SessionFactory sessionFactory, Class domainClass, Object target, Object[] delegates) {
		if ( interfaces == null || interfaces.length < 1) {
			throw new IllegalArgumentException( "attempting to build proxy without any superclass or interfaces" );
		}
		final ProxyFactory factory = new ProxyFactory();
//		if ( superClass != null ) {
//			factory.setSuperclass( superClass );
//		}
		if ( interfaces != null && interfaces.length > 0 ) {
			factory.setInterfaces( interfaces );
		}
		try {
			final ProxyObject proxy = ( ProxyObject ) factory.createClass().newInstance();
			proxy.setHandler(new MethodHandlerAdapter(MethodInterceptor.create(sessionFactory, domainClass, target, delegates, interfaces)));
			return factory.createClass();
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
